const app = getApp();
// const util = require('../../utils/util.js');
const utils = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    CurrentPage: 1,
    loadingMore: 1, // -1 加载中
    title: '',
    navBarHeight: 60,
    myCardId: 0,    //我自己的名片id
    keyword: '',
    tagindex: 1,
    staffList: [],
    latitude: 0,
    longitude: 0,
    cardUser: {cid:0, mobile: '', saleUid: 0, saleStaffId: 0}, //玖玖卡
    spikeList: [],  //爆品秒杀
    packPid: 0,     //玖玖卡套餐pid
    regionType: 1,
    cityId: 0,
    sorttype: 1,//0 综合, 1 距离, 2 折扣, 3 促销折扣
    industryId: 1,  //行业id
    classList: [],
    brandList:[],   //品牌列表
    shopList: [],   //美团商家列表
    listType: 2,    //列表类型: 1 玖玖客商家数据, 2 美团数据
    revUid: 0,        //玖玖卡推荐人
    isAccredit: false,//是否已经授权头像昵称
    canIUseGetUserProfile: false, 
    meituan: {
      cityId: 0,      //美团城市id
      cateId: 0,      //一级类目id
      cateId2: 0,     //二级类目id
      sortType: 1,    //1 距离最近,6 销量升序,7 销量降序, 14 评分升序, 15 评分降序,18 价格升序,19 价格降序
      distance: 0,    //距离范围:米
      brandTab: 1,    //商家tab: 0 未选中, 1 品牌商家, 2 全部商家
      cateTab: 0,     //分类tab: 0 未选中, 1 全部分类, 2 附近, 3 智能排序
      tabState: 0,    //tab弹框是否显示: 0 不显示, 1显示
      secendCates: [], //美团二级分类
      pagePath: '',    //外卖链接
    },
    share: {cardId: 0, saleUid: 0 ,type: 0},    //分享带过来的参数
  },

  staffListener(e) {
    let that = this;
    let meituan = this.data.meituan;
    this.data.keyword = e.detail,
    this.data.CurrentPage = 1;

    if(that.data.listType == 2){     
      meituan.brandTab = 2;
      meituan.cateId = that.data.industryId == 1 ? 0 : meituan.cateId;      
      that.setData({
        meituan: meituan
      })
      that.meituanSearch();
    }
    else {
      that.getStaffListByDistance(that.data.cityId);
    }
  },

  changeSort: function (e) {
    let sort = e.currentTarget.dataset.sort;
    this.data.regionType = 1;
    this.setData({
      sorttype: sort,
      CurrentPage: 1,
      staffList: []
    })
    this.getStaffListByDistance(this.data.cityId);
  },

  getMyCard: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + app.globalData.myUserInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            let staffid = res.data.Data.Id;     
            that.data.shareTitle = res.data.Data.Company;
            utils.isAccredit(function (isAccredit) {
              that.setData({
                isAccredit: isAccredit, //是否授权头像
                myCardId: staffid
              })
            });          
          }
        }
      },
    })
  },

  toMyJJK: function () {
    wx.reLaunch({
      url: '/pages/index/index?id=' + this.data.myCardId + '&isPlatform=1',
    })
  },

  toCuxiaoDetail: function (e) {
    let cardId = e.currentTarget.dataset.cardid;
    wx.navigateTo({
      url: '../promotionDetail/index?cardId=' + cardId,
    })
  },

  tapClassSelect: function (e) {
    let index = e.currentTarget.dataset.index;  // 选择的索引,从0开始
    let cid = e.currentTarget.dataset.cid;
    let tagindex = this.data.tagindex;
    let meituan = this.data.meituan;
    let isMeituan = this.isMeituan(cid);
    if(index == 1){
      this.toMeituan(); //外卖类目，跳转到美团
      return;
    }    
    if(isMeituan){   
      meituan.cateId = cid;   //美团一级类目id
      meituan.cateId2 = 0;    //美团二级类目id
      meituan.cateTab = 0;    //未选中
      meituan.brandTab = index == 0 ? 1 : 2;  // 1 品牌商家, 2 全部商家
      meituan.secendCates = []; //切换一级类目时，清空二级类目
      tagindex = 1;
     } 

    this.setData({
      industryId: cid,
      listType:  isMeituan ? 2 : 1,
      tagindex: tagindex,
      CurrentPage: 1,
      staffList: [],
      shopList: [],
      keyword: '',
      meituan: meituan
    })

    if(!isMeituan){
      this.getStaffListByDistance(this.data.cityId);  //玖玖客商家数据
    }else if(meituan.brandTab == 2){
      this.meituanSearch();  
    } 
  },
  
  // 获取店铺行业
  getIndustryList: function () {
    let list =[];
    list.push({StoreIid: 1, Title: "品牌", image: "/images/home/1.png"});
    list.push({StoreIid: 4, Title: "外卖", image: "/images/home/4.png"});
    list.push({StoreIid: -1, Title: "推荐", image: "/images/home/5.png"});
    list.push({StoreIid: 226, Title: "餐饮", image: "/images/home/226.png"});
    list.push({StoreIid: 3, Title: "休闲娱乐", image: "/images/home/3.png"});

    list.push({StoreIid: 388, Title: "结婚", image: "/images/home/388.png"});
    list.push({StoreIid: 2, Title: "丽人", image: "/images/home/2.png"});
    list.push({StoreIid: 289, Title: "教育培训", image: "/images/home/289.png"});
    list.push({StoreIid: 389, Title: "亲子", image: "/images/home/389.png"});
    list.push({StoreIid: 226, Title: "全部", image: "/images/home/0.png"});
    this.setData({
      classList: list
    })
  },

  getCardProduct: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/product/GetCardProduct',
      success: function (res) {
        if (res.data.Code == 0) {
          let list = res.data.Data;
          if (list.length > 1) {
            that.data.packPid = list[1].Pid;
          }
          that.getNearbyProductList();
        }
      }
    })
  },

  // 爆品特惠（9.9）
  getNearbyProductList: function () {
    let url = app.globalData.host + '/api/Product/GetNearbyProductList';
    this.getProductList(url);    
  },
  //云加盟
  getJoinList: function(){
    let url = app.globalData.host + '/api/Product/GetJoinList';
    this.getProductList(url);    
  },
  getProductList: function(url){
    let that = this;
    wx.showLoading({title: '加载中...',mask: true})
    wx.request({
      url: url,
      data: {
        uid: app.globalData.userInfo.Uid,
        latitude: that.data.latitude,
        longitude: that.data.longitude,
        page: that.data.CurrentPage,
        pageSize: 10
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          that.setData({
            spikeList: that.getData(res.data.Data.Items),
            loadingMore: res.data.Data.TotalPages
          })
        } else {
          utils.showModal(res.data.Message);
        }
      },
    })
  },
  // 云加盟更多、爆品秒杀更多
  loadMoreProduct: function () {
    var that = this;
    if (that.data.loadingMore > 1 && that.data.CurrentPage < that.data.loadingMore) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      if(that.data.tagindex == 3){
        that.getNearbyProductList();
      }
      if(that.data.tagindex == 4){
        that.getJoinList();
      }      
    }
  },
  //地图导航
  openMapLocation: function (e) {
    let Latitude = e.currentTarget.dataset.latitute;
    let Longitude = e.currentTarget.dataset.longitude;
    let Company = e.currentTarget.dataset.company;
    wx.showModal({
      title: '提示',
      content: '是否打开地图导航',
      success: function (res) {
        if (res.confirm) {
          wx.openLocation({
            latitude: Latitude,
            longitude: Longitude,
            scale: 28,
            name: "点击右边打开地图导航",
            address: Company
          })
        }
      }
    })
  },

  toProDetail: function (e) {
    let pid = e.currentTarget.dataset.pid;
    let seltoid = e.currentTarget.dataset.seltoid;
    let staffid = e.currentTarget.dataset.staffid;
    let saleUid =  app.globalData.userInfo.Uid;
    if(this.data.tagindex == 3){
        if(this.data.share.saleUid >0){
          saleUid = this.data.share.saleUid;    //通过分享链接进来
        }else if(this.data.myCardId <= 0){
          saleUid = this.data.cardUser.saleUid; //自己没有名片，用玖玖卡分享人当推荐人
        }        
    }
    let url = '/pages/joinDetail/index?pid=' + pid + '&seltoid=' + seltoid + '&saleUid=' + saleUid + '&jump=1&proStaffid=' + staffid;
    if(this.data.tagindex == 4){
      url = '/pages/joinDetail/index?pid=' + pid + '&seltoid=' + seltoid + '&jump=11';
    }
    wx.navigateTo({url: url});
  },


  getMobile: function (e) {
    let that = this;
    utils.getMobile(e, function (mobiles) {
      if (mobiles) {
        that.toRefuel();
      } else {
        wx.showToast({
          title: '请授权手机号',
          mask: true
        })
      }
    })
  },

  toRefuel: function () {
    let that = this;
    let platformType = '';
    let authCode = '';
    wx.request({
      url: app.globalData.host + '/api/Petrol/GetAuthCode?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          platformType = res.data.Data.ChannelId;
          authCode = res.data.Data.Code;
          wx.navigateTo({
            url: 'plugin://ty-plugin/index?platformType=' + platformType + '&authCode=' + authCode,
          })
        } else {
          utils.showModal(res.data.Message);         
        }
      }
    })
  },

  toCardDetail: function (e) {
    let id = e.currentTarget.dataset.id;
     wx.reLaunch({
        url: '/pages/index/index?id=' + id + '&isPlatform=1',
      })
  },

  changeTagindex: function (e) {
    let index = e.currentTarget.dataset.index;
    let listType = index== 1 ?  2: 1;
    this.setData({      
      tagindex: index,
      CurrentPage: 1,
      staffList: [],
      regionType: 1,
      listType: listType
    })

    if(index == 4){
      this.getJoinList();
    }
    else if (index == 3) {
      // this.getCardProduct();
      this.getNearbyProductList();
      this.getSaleStaff();
    } else {
      this.getBrandList();
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    this.getOnloadParam(e);
    this.getLocation();
    this.getIndustryList();
    this.getBrandList();
    
    let isUserProfile = wx.getUserProfile ? true : false; //是否调用微信头像
    this.setData({
      navBarHeight: app.globalData.navBarHeight,
      canIUseGetUserProfile: isUserProfile
    })
    if(this.data.revUid > 0){
      this.receiveJJK(this.data.revUid);  //带此参数,自动领玖玖卡 2022-04-11
    }
    if(app.globalData.isFriendState == 1){
      utils.showToast('请前往小程序体验所有功能');  
    }
  },

 /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (app.globalData.userInfo) {
      that.getJJKInfo();
      that.getMyCard();      
    } else {
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  getOnloadParam: function (e) {
    if (!e){ return; } 
    let params = decodeURIComponent(e.scene);
    if (params && params != 'undefined') {  //扫描小程序二维码进入
      let plist = '';
      let type = 0;
      if (params.indexOf('p-') != -1) {
        type = params.match(/t-(\S*)\*p/)[1];//路由
        let param = params.match(/p-(\S*)/)[1];//参数
        plist = param.split('_');
      }
      if (type == 1) {  //来源于服务商海报
        let cardId = plist[0];
        let source = plist[2];
        this.data.revUid = plist[1];
      }
      if (type == 2) {  //来源于爆品秒杀分享     
      }
    }else{
      if(e.id){
        this.data.share.cardId = e.id;
      }
      if(e.saleUid){
        this.data.share.saleUid = e.saleUid;
      }
      if(e.type){
        this.data.share.type = e.type;  //1 服务商海报分享, 2 爆品秒杀分享
      }
      if(e.revUid){
        this.data.revUid = e.revUid;
      }           
    }
  },

  getStaffListByDistance: function (cityId) {
    let that = this;
    let tagindex = that.data.tagindex;
    let sorttype = that.data.sorttype;
    let regionType = that.data.regionType;//1当前市的数据2其他市的数据
    let range = 2;
    if (tagindex == 4) {
      range = 3;
      sorttype = 0;
    }

    let data= {
      cardItemId: 0,
      range: range,
      storeAppId: app.globalData.storeAppId,
      lat: that.data.latitude,
      lng: that.data.longitude,
      keyword: that.data.keyword,
      page: that.data.CurrentPage,
      cityId: cityId,
      cityType: regionType,
      sortType: sorttype,
      industryId: that.data.industryId
    }

    wx.showLoading({title: '加载中...',mask: true})
    wx.request({
      url: app.globalData.host + '/api/staff/GetListBySale',
      data: data,
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if(res.data.Code != 0){
          utils.showModal(res.data.Message);         
          return;
        }      

        let staffList = res.data.Data.Items;
        for (let i = 0; i < staffList.length; i++) {
          staffList[i].Avater = utils.formatAvater(staffList[i].Avater, 'https://static.711688.net.cn/upload/card/source/');
          staffList[i].Discount = 100 - staffList[i].UseDiscount;
          staffList[i].ShowDiscount = staffList[i].Discount / 10;
          staffList[i].Distance = parseFloat(staffList[i].Distance).toFixed(2);
          staffList[i].Distances = parseFloat(staffList[i].Distance / 1000).toFixed(2);
        }
        if (that.data.CurrentPage != 1) {
          let preList = that.data.staffList;
          staffList = preList.concat(staffList);
        } 
        if(staffList.length==0){
          utils.showToast('暂无数据');
        }
        that.setData({
          staffList: staffList,
          loadingMore: res.data.Data.TotalPages
        })
      },
    })
  },

  // 获取地理位置  
  getLocation: function () {
    let that = this;
    utils.getLocation((location)=>{
      that.data.latitude = location.lat;
      that.data.longitude = location.lng;
      that.getCurrentCity(location.lat, location.lng);      
    }, 1);   
  },
  
  getCurrentCity: function (lat, log) {
    let that = this;
    that.data.regionType = 1;
    if(lat <= 0 ){
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/Tool/GetRegionByGeo?lat=' + lat + '&lng=' + log,
      success: function (res) {
        let title = '';        
        if (res.data.Code == 0) {          
          that.data.cityId = res.data.Data.CityId;
          title = res.data.Data.CityName ? res.data.Data.CityName: '';
          title = title.length <=4 ? title : title.substr(0,3) + '...';
          that.meituanPreSearch(res.data.Data.ProvinceName,res.data.Data.CityName);
        }
        that.setData({
          title: title
        })
      }
    })
  },  

  // 加载更多
  loadMore: function () {
    let that = this;    
    if (that.data.loadingMore > 1 && that.data.CurrentPage < that.data.loadingMore) {
      that.setData({
        CurrentPage: that.data.CurrentPage + 1
      })
      
      if(that.isMeituan(that.data.industryId)){
        that.meituanSearch();   //美团数据
      }else{
        that.getStaffListByDistance(that.data.cityId);
      }      
    } 
  },

  getJJKInfo: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardExists?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          var item = res.data.Data;
          if (res.data.Data) {
            let cardUser = that.data.cardUser;
            cardUser.cid = item.Cid;
            cardUser.saleUid = item.SaleUid;
            cardUser.mobile = item.Phone;
            that.setData({
              cardUser: cardUser,
            })
          }
        } else {
          utils.showModal(res.data.Message);          
        }
      }
    })
  },
  //获取玖玖卡分享人名片
  getSaleStaff: function(){
    let that = this;
    if(that.data.myCardId > 0 || that.data.cardUser.saleStaffId > 0){
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/staff/GetStaffIdByUid?uid=' + that.data.cardUser.saleUid,
      success: function (res) {
        if (res.data.Code == 0 && res.data.Data) {
            that.data.cardUser.saleStaffId = res.data.Data.Id;
        } 
      }
    })
  },
  //编辑页面
  toEdit: function(e){
     let uid = e.currentTarget.dataset.uid;
    wx.navigateTo({
      url: '/pages/h5page/index?url=' + encodeURIComponent(app.globalData.webhost + 'setdisplay.html?uid=' +  uid),
    })
  },
  onReachBottom: function () {
    if (this.data.tagindex == 1 || this.data.tagindex == 4) {
      this.loadMore();
    }
  },

  getData: function(items){
    let that = this;
    let list = items;
    if (that.data.CurrentPage != 1) {
      let preList = that.data.spikeList;
      list = preList.concat(list);
    }
    let discount = 0;
    for (let i = 0; i < list.length; i++) {
      list[i].status = '抢购中';
      list[i].showProduct = true;

      if (list[i].State == 1) {//已下架
        list[i].status = '已下架';
        list[i].showProduct = false;
      }
      if (list[i].State == 3) {
        list[i].status = '已拒绝';
        list[i].showProduct = false;
      }
      if (list[i].State == 4) {
        list[i].status = '审核中';
        list[i].showProduct = false;
      }
      if (list[i].State == 0) {
        if (list[i].StockNumber < 1) {
          list[i].status = '已售罄';
        }
        if (list[i].extend.SendEndTime) {
          let nowTime = new Date();
          let endTime = new Date(Date.parse(list[i].extend.SendEndTime.replace(/-/g, "/")));
          if (nowTime > endTime) {
            list[i].status = '已售罄';
          }
        }        
      }
     

      if (list[i].Pid == that.data.packPid) {
        list[i].showProduct = false;
      }      
      if(that.data.myCardId > 0){
        discount = list[i].extend.discount ? list[i].extend.discount : 40;  //默认 40%
      }
      list[i].extend.BrokeragePriceDiscount = parseFloat(list[i].extend.BrokeragePrice * discount * 0.01).toFixed(2);
      list[i].extend.Avater = utils.formatAvater(list[i].extend.Avater, 'https://static.711688.net.cn/upload/card/source/');

      if (list[i].extend.Distance >= 1000) {
        list[i].extend.Distances = parseFloat(list[i].extend.Distance / 1000).toFixed(2);
      }      

      if (list[i].ShowImg.indexOf('ps') != -1) {
        list[i].ShowImg = utils.formatAvaterByProHead(list[i].ShowImg);
      } else {
        list[i].ShowImg = utils.formatAvater(list[i].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
      }       
    }
    return list;      
  },
  //品牌商家
  getBrandList: function(){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/meituan/getBrandList',
      success: function (res) {
        if (res.data.Code == 0) {          
          that.setData({
            brandList: res.data.Data
          })
        }
      }
    })   
  },  
  //获取美团搜索参数
  meituanPreSearch:function(province,city){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/meituan/preSearch?province=' + province + '&city=' + city,
      success: function (res) {
        if (res.data.Code == 0) {          
          let data = res.data.Data;
          let meituan = that.data.meituan;
          meituan.cityId = data.cityId;
          meituan.cateId = data.cateId;
        }
      }
    })
  },
  //美团搜索
  meituanSearch:function(){
    let that = this;
    let meituan = that.data.meituan;
    if(that.data.longitude<=0){
      utils.showToast('请开启手机定位再重试');
      this.getLocation();
      return;
    }
    if(meituan.cityId<=0){
      utils.showToast('缺少城市参数'); return;
    }  
    if(that.data.CurrentPage <=1){
      that.data.shopList = [];
    }      
    this.setData({
      loadingMore: -1 // -1 加载中
    })
    wx.request({
      url: app.globalData.host + '/api/meituan/search',
      data: {
        uid: app.globalData.userInfo.Uid,
        key: that.data.keyword,
        cityId: meituan.cityId,
        cateId: meituan.cateId,
        cateId2: meituan.cateId2,
        distance: meituan.distance,
        sortType: meituan.sortType,
        lng: that.data.longitude,
        lat: that.data.latitude,
        page: that.data.CurrentPage
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          let shopList = that.data.shopList;
          for(let i = 0; i < res.data.Data.Items.length; i++){           
            let item =  res.data.Data.Items[i];
            item.DealBaseInfo.realPrice = (item.DealBaseInfo.realPrice/100).toFixed(2);
            item.DealBaseInfo.marketPrice = (item.DealBaseInfo.marketPrice/100).toFixed(0);
            item.ShopInfo.pricePerson = (item.ShopInfo.pricePerson/100).toFixed(0);
            item.ShopInfo.shopPowers=[];         
            for(let j=0; j<50; j+= 10){
              let num = item.ShopInfo.shopPower - j;
              if(num >= 10){
                item.ShopInfo.shopPowers.push('star10.png'); //满星
              }else if(num < 10 & num > 0){
                item.ShopInfo.shopPowers.push('star5.png');  //半颗星
              }else if(num < 10){
                item.ShopInfo.shopPowers.push('star0.png');  //没星
              }             
            }
            if(item.ShopInfo.distance > 1000){
              item.ShopInfo.distance = Math.round(item.ShopInfo.distance/100)/10  + ' km'
            }else{
              item.ShopInfo.distance += ' m';
            }
            if(!that.isShopExists(shopList, item.ShopInfo.shopName)){
              shopList.push(item);
            }            
          }
          that.setData({
            shopList: shopList,
            loadingMore: res.data.Data.PageModel.TotalPages
          })
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },
  //美团二级类目
  getMeituanCate: function(){
    let that = this;
    let meituan = this.data.meituan;
    if(meituan.secendCates.length > 0){
      return; //减少重复的服务器请求
    }
    wx.request({
      url: app.globalData.host + '/api/meituan/getCateList?cityId=' + meituan.cityId + '&cateId=' + meituan.cateId,
      success: function (res) {
        if (res.data.Code == 0) {          
          let categories = res.data.Data.categories;
          meituan.secendCates = [];
          for(let key in categories){
            meituan.secendCates.push({cateId2: key, Name: categories[key]});
          }
          that.setData({
            meituan: meituan
          })
        }
      }
    })
  },
  //品牌商家tab
  changeBrandTab: function(e){
    let cid = this.data.industryId;
    let meituan = this.data.meituan;
    meituan.brandTab = e.currentTarget.dataset.tab;
    if(meituan.brandTab == 2){
      meituan.cateId = 0;
      meituan.cateId2 = 0;
      cid = 0;  //0 表示全部商家
      if(this.data.shopList.length <= 0){
        this.meituanSearch();
      }
    }
    this.setData({
      meituan: meituan,
      industryId: cid
    })
  },
  //全部商家tab
  changeCateTab: function(e){
    let tab =  e.currentTarget.dataset.tab;
    let meituan = this.data.meituan;
    meituan.tabState = meituan.tabState == 1 ? 0 : 1; //点击同一个类目时，隐藏tab弹框
    if(meituan.cateTab != tab){
      meituan.tabState = 1;   //切换类目时，显示tab弹框
    }
    meituan.cateTab = tab;
    this.setData({
      meituan: meituan
    })
    if(tab == 1 && meituan.tabState ==1){
      this.getMeituanCate();
    }
  },

  //美团分类
  changeMeituanCate: function(e){
    let cateId2 = e.currentTarget.dataset.key;
    if(cateId2 == this.data.meituan.cateId2){
      cateId2 = 0;
    }
    this.data.meituan.cateId2 = cateId2;
    this.changeMeituan();
  },
  //美团附近
  changeMeituanDistance: function(e){
    this.data.meituan.distance = e.currentTarget.dataset.key;
    this.changeMeituan();
  },
  //美团排序
  changeMeituanSort: function(e){
    this.data.meituan.sortType = e.currentTarget.dataset.key;
    this.changeMeituan();
  },
  changeMeituan: function(){
    let meituan = this.data.meituan;
    meituan.tabState = 0; //隐藏tab弹框
    this.setData({
      meituan: meituan,
      CurrentPage: 1,
      loadingMore: -1
    })
    this.meituanSearch();
  },
 //美团店铺详情
 toDetail: function(e){
  let that = this;
  let index = e.currentTarget.dataset.index;
  let key = that.data.shopList[index].ShopInfo.shopName;  //按店铺店铺名称搜索
  let meituan = this.data.meituan;
  wx.navigateTo({
    url: '/pages/meituan/detail/index?cityId=' + meituan.cityId + '&cateId=' + meituan.cateId + '&key=' + key,
  })
},
  //美团搜索
  toSearch: function(e){
    let key = e.currentTarget.dataset.key;
    let cateId = e.currentTarget.dataset.cateid;
    let meituan = this.data.meituan;
    wx.navigateTo({
      url: '/pages/meituan/search/index?cityId=' + meituan.cityId  + '&cateId=' + cateId + '&key=' + key,
    })
  },
  //跳转美团
  toMeituan: function(){
   let that = this;
   that.getMeitunLink(()=>{
      if(!that.data.meituan.pagePath){
        utils.showToast('美团链接加载失败, 请重试');
        return;
      }
      wx.navigateToMiniProgram({appId: 'wxde8ac0a21135c07d',path: that.data.meituan.pagePath})
    })
  },
  getMeitunLink: function(callback){
    let that = this;
    if(that.data.meituan.pagePath){
      callback();
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/meituan/getLink?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {          
          that.data.meituan.pagePath = res.data.Data;
          callback();
        }
      }
    })
  },
  //是否是美团数据
  isMeituan: function(cid){
    let that = this;
    let indexList ='0,3,4,5,6,7,8,9';
    let index = -1;
    for(let i=0; i< that.data.classList.length;i++){
      let item = that.data.classList[i];
      if(item.StoreIid == cid){
        index = i; break;
      }
    }
    return indexList.indexOf(index) > -1;
  },
  isShopExists: function(shopList,shopName){
    for(let i = 0; i < shopList.length; i++){
      if(shopList[i].ShopInfo.shopName == shopName){
        return true;
      }
    }
    return false;
  },  
  //领玖玖卡
  receiveJJK: function (saleUid) {
    let that = this;
    console.log('领玖玖卡 revUid:',saleUid);
    if (app.globalData.userInfo) {
      let jjCard = app.globalData.jjCard;
      wx.request({
        url: app.globalData.host + '/api/Coupon/ReceiveCard?code=0&cardItemId=' + jjCard.Id + '&uid=' + app.globalData.userInfo.Uid + '&saleUid=' + saleUid,
        success: function (res) {                 
        }
      })
    } else {
      setTimeout(function () {
        that.receiveJJK(saleUid);
      }, 1000)
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    let that = this;
    let path = '/pages/indexDefault/index';
    let shareTitle ='过好日子，用玖玖客';        
    if (that.data.myCardId > 0) {
      shareTitle = that.data.shareTitle
      path = '/pages/indexDefault/index?id=' + that.data.myCardId  +  '&source=2&revUid=' + app.globalData.myUserInfo.Uid;
    }else if(that.data.cardUser.saleUid > 0){
      path = '/pages/indexDefault/index?id=' + that.data.myCardId  +  '&source=2&revUid=' + that.data.cardUser.saleUid;
    } 

    //爆品秒杀分享
    if(that.data.tagindex == 3){
      //分享人有名片，则带上自己的id,否则带上玖玖卡推荐人id
      let cardId = that.data.myCardId > 0 ? that.data.myCardId : that.data.cardUser.saleStaffId;
      let saleUid = that.data.myCardId > 0 ?  app.globalData.myUserInfo.Uid : that.data.cardUser.saleUid;
      path = '/merchant/merchants/nearbyCoupon/index?id=' + cardId + '&saleUid=' + saleUid +  '&source=2&type=2';
    }
    console.log(path)
    return {
      imageUrl: that.data.meituan.shareImg,
      title: shareTitle,
      path: path,
      success: function (res) {
        utils.showToast('分享成功');
      }
    }
  },
  
  //分享朋友圈
  onShareTimeline: function () {
    let that = this;
    let path = '';
    let shareTitle ='过好日子，用玖玖客';    
    if (that.data.myCardId > 0) {
      shareTitle = that.data.shareTitle
      path = 'id=' + that.data.myCardId  +  '&source=2&revUid=' + app.globalData.myUserInfo.Uid + '&isFriendState=1';
    }else if(that.data.cardUser.saleUid > 0){
      path = 'id=' + that.data.myCardId  +  '&source=2&revUid=' + that.data.cardUser.saleUid + '&isFriendState=1';
    }
    //爆品秒杀分享
    if(that.data.tagindex == 3){
      let cardId = that.data.myCardId > 0 ? that.data.myCardId : that.data.cardUser.saleStaffId;
      let saleUid = that.data.myCardId > 0 ?  app.globalData.myUserInfo.Uid : that.data.cardUser.saleUid;
      path = 'id=' + cardId + '&saleUid=' + saleUid + '&source=2&type=2&isFriendState=1';
    }
    console.log(path); 
    return {
      title: shareTitle,
      query:  path,
      imageUrl: ''
    }
  },

  //授权头像昵称
  getUserProfile: function (e) {
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', 
      success: (res) => {
        utils.AuthorizeUserInfo(res, '', function (flag) {
          that.setData({isAccredit: flag})     
          that.toMeituan();     
        });   
      }
    })
  },
  //添加卖券商品
  toAddProduct: function () {
    let that = this;
    let staffid = wx.getStorageSync('cardId');
    let url = '/pages/h5page/index?url=serviceAgreement.html';
    if (staffid) {
      wx.request({
        url: app.globalData.host + '/api/staff/GetStaffExtend?staffid=' + staffid + '&keyword=29',
        success: function (res) {
          if (res.data.Data) {
            // 已经签了合同并且上传营业执照
            url = '/merchant/merchants/addProduct/index?seltoid=' + that.data.cardUid;
            wx.navigateTo({url: url})
          } else {
            wx.navigateTo({url: url})
          }
        }
      })
    }
  },

})